﻿//**********************************************************
//Copyright(C)2010 By 波特商网公司 版权所有。
//
//文件名：Utility.cs
//文件功能：常用公共方法类
//
//创建标识：齐李平 || 2011-04-18
//
//修改标识：2011-04-18
//修改描述：新增窗体显示到Control方法
//**********************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Hmc.IM.Common.Base;


namespace Hmc.IM.Common
{
    /// <summary>
    /// 常用公共方法类
    /// </summary>
    public class Utility
    {
        #region 加载窗体到容器Method
        /// <summary>
        /// 将窗体显示到Control上
        /// </summary>
        /// <param name="frm">窗体</param>
        /// <param name="parentControl">加载窗体的容器</param>
        /// <param name="isClear">是否清除容器里的内容</param>
        public static void ShowFormInControl(Form frm, Control parentControl, bool isClear = false)
        {
            ShowFormInControl(frm, parentControl, null, isClear);
        }

        /// <summary>
        /// 将窗体显示到Control上
        /// </summary>
        /// <param name="frm">窗体</param>
        /// <param name="parentControl">加载窗体的容器</param>
        /// <param name="tag">窗体数据</param>
        /// <param name="isClear">是否清除容器里的内容</param>
        public static void ShowFormInControl(Form frm, Control parentControl, object tag, bool isClear = false)
        {
            //是否存在窗体
            bool isExits = false;
            int count = parentControl.Controls.Count;//窗体总数量

            for (int i = count; i > 0; i--)
            {
                //如果存在则直接显示
                if (frm.Name == parentControl.Controls[i - 1].Name)
                {
                    if (isClear == false)
                    {
                        frm = parentControl.Controls[i - 1] as Form;
                        isExits = true;
                        //添加日志
                        //Logger.Write("Store", LoginUserEntity.SystemUserId.ToString(), LoginUserEntity.UserName, "" + frm.Text + "窗体存在不销毁", "检测到“" + frm.Text + "”存在，按要求不销毁。");
                    }
                    else
                    {
                        //添加日志
                        //Logger.Write("Store", LoginUserEntity.SystemUserId.ToString(), LoginUserEntity.UserName, "" + frm.Text + "窗体存在销毁", "检测到“" + frm.Text + "”窗体存在，按要求销毁。");
                        parentControl.Controls[i - 1].Dispose();
                        GC.Collect();
                    }
                }
                else
                {
                    //添加日志
                    //Logger.Write("Store", LoginUserEntity.SystemUserId.ToString(), LoginUserEntity.UserName, "销毁" + parentControl.Controls[i - 1].Text + "窗体", "销毁" + parentControl.Controls[i - 1].Text + "”窗体。");
                    //消毁窗体
                    if (isClear) { parentControl.Controls[i - 1].Dispose(); GC.Collect(); }

                }
            }

            frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frm.ShowIcon = false;
            frm.ShowInTaskbar = false;
            frm.BackColor = Color.White;
            frm.TopLevel = false;
            frm.Dock = DockStyle.Fill;

            if (tag != null) frm.Tag = tag;

            //不存在添加到父容器中
            if (!isExits)
            {
                parentControl.Controls.Add(frm);
                //Logger.Write(".Store", LoginUserEntity.SystemUserId.ToString(), LoginUserEntity.UserName, "添加" + frm.Text + "窗体", "添加" + frm.Text + "”窗体。");
            }
            frm.Show();
            frm.BringToFront();
            frm.Focus();

        }

        /// <summary>
        /// 显示新的窗体
        /// </summary>
        /// <param name="frm">呈现的窗体</param>
        /// <param name="parentControl">父容器（取this可把当前窗体当容器使用）</param>
        public static void ShowWindows(Form frm, Control parentControl)
        {
            try
            {
                ShowFormInControl(frm, parentControl);
                //frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                //frm.ShowIcon = false;
                //frm.ShowInTaskbar = false;
                //frm.BackColor = Color.White;
                //frm.TopLevel = false;
                //frm.Dock = DockStyle.Fill;
                //frm.Parent = parentControl;
                //frm.Show();
                //frm.BringToFront();
                //frm.Focus();
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 获得枚举列表Method
        /// <summary>
        /// 获得枚举列表
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="isAddHead"></param>
        /// <returns></returns>
        public static List<DropdownListEntity> GetEnumList(Type t, bool isAddHead = true)
        {
            List<DropdownListEntity> list = new List<DropdownListEntity>();

            if (t.IsEnum == false) return list;

            var values = System.Enum.GetValues(t);

            foreach (var item in values)
            {
                //list.Add(new DropdownListEntity { Text = ((System.Enum)item).GetDescription(), Value = (int)item });
            }

            if (isAddHead) list.Insert(0, new DropdownListEntity { Text = "--请选择--", Value = -1 });

            return list;
        }


        /// <summary>
        /// 获得枚举列表
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="removeValue">需要排除的Value</param>
        /// <param name="isAddHead">是否添加头部</param>
        /// <returns></returns>
        public static List<DropdownListEntity> GetEnumList(Type t, List<int> removeValue, bool isAddHead = true)
        {
            List<DropdownListEntity> list = new List<DropdownListEntity>();

            if (t.IsEnum == false) return list;

            var values = System.Enum.GetValues(t);

            foreach (var item in values)
            {
                if (removeValue != null)
                {
                    var val = (from p in removeValue where p == (int)item select p).SingleOrDefault();
                    if (val != (int)item)
                    {
                        //list.Add(new DropdownListEntity { Text = ((System.Enum)item).GetDescription(), Value = (int)item });
                    }
                }
                //else list.Add(new DropdownListEntity { Text = ((System.Enum)item).GetDescription(), Value = (int)item });
            }

            if (isAddHead) list.Insert(0, new DropdownListEntity { Text = "--请选择--", Value = -1 });

            return list;
        }

        #endregion

        #region 获取唯一随机数Method
        /// <summary>
        /// 获取唯一数
        /// </summary>
        /// <returns></returns>
        public static string GetUniqueNum()
        {
            StringBuilder sb = new StringBuilder(DateTime.Now.ToString("yyyyMMddHHmmss"));

            Random random = new Random();

            Thread.Sleep(1);
            while (sb.Length < 16)
            {
                sb.Append(random.Next(0, 9));
            }

            return sb.ToString();
        }

        /// <summary>
        ///  获取银联交易流水
        /// </summary>
        /// <returns></returns>
        public static string GetTransactionFlow()
        {
            Thread.Sleep(1);
            DateTime dt = DateTime.Now;
            return dt.ToString("HHmmss");
        }
        #endregion

        #region 验证是否具有权限Method
        /// <summary>
        /// 检查权限(传0直接返回True)
        /// </summary>
        /// <param name="point">权限点</param>
        /// <returns></returns>
        public static bool HadPermissions(int point)
        {
            if (point == 0) return true;

            var query = from p in LoginUserEntity.PermissionsPoint where p == point select p;
            if (query == null || query.Count() == 0) return false;
            else return true;
        }
        #endregion

        #region 后台线程调用Method
        /// <summary>
        /// 后台线程工作（不带返回值/不带参数）
        /// </summary>
        public static void BackgroundWorker(Action doWork, Action runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    doWork();
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted();
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（不带返回值/1个参数）
        /// </summary>
        public static void BackgroundWorker<T>(T t, Action<T> doWork, Action runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    doWork(t);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted();
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（不带返回值/2个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2>(T1 t1, T2 t2, Action<T1, T2> doWork, Action runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    doWork(t1, t2);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted();
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（不带参数）
        /// </summary>
        public static void BackgroundWorker<TResult>(Func<TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork();
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（1个参数）
        /// </summary>
        public static void BackgroundWorker<T, TResult>(T t, Func<T, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync(t);
        }

        /// <summary>
        /// 后台线程工作（2个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, TResult>(T1 t1, T2 t2, Func<T1, T2, TResult> doWork, Action<object> runWorkerCompleted)
        {

            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（3个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3, Func<T1, T2, T3, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    e.Result = ex;
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（4个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3, T4 t4, Func<T1, T2, T3, T4, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3, t4);
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                    Logger.Write(ex);
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（5个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, T4, T5, TResult>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, Func<T1, T2, T3, T4, T5, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3, t4, t5);
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                    Logger.Write(ex);
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（6个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, T4, T5, T6, TResult>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, Func<T1, T2, T3, T4, T5, T6, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3, t4, t5, t6);
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                    Logger.Write(ex);
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（7个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, T4, T5, T6, T7, TResult>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, Func<T1, T2, T3, T4, T5, T6, T7, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3, t4, t5, t6, t7);
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                    Logger.Write(ex);
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 后台线程工作（8个参数）
        /// </summary>
        public static void BackgroundWorker<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> doWork, Action<object> runWorkerCompleted)
        {
            BackgroundWorker worker = new BackgroundWorker();

            //线程工作
            worker.DoWork += new DoWorkEventHandler((sender, e) =>
            {
                try
                {
                    e.Result = doWork(t1, t2, t3, t4, t5, t6, t7, t8);
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                    Logger.Write(ex);
                }
            });

            //线程完成工作
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, e) =>
            {
                runWorkerCompleted(e.Result);
                //消毁线程
                ((BackgroundWorker)sender).Dispose();
            });

            worker.RunWorkerAsync();
        }

        #endregion

        #region [获取未完成标识]

        /// <summary>
        /// 获取未完成标识
        /// </summary>
        /// <param name="windown">需标识的窗体</param>
        public static void GetNontComplete(Form windown)
        {
            Font f = new Font("华文新魏", 16, FontStyle.Bold);
            Brush b = new SolidBrush(Color.FromArgb(255, 255, 0, 0));
            string addText = "未完成";

            Graphics ghs = Graphics.FromHwnd(windown.Handle);
            SizeF size = ghs.MeasureString(addText, f);
            ghs.Dispose();

            Bitmap map = new Bitmap(Convert.ToInt32(size.Width), Convert.ToInt32(size.Width));
            Graphics g = Graphics.FromImage(map);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.DrawImage(map, 0, 0, map.Width, map.Height);

            //g.TranslateTransform(16,16);
            Matrix transform = g.Transform;
            float shearX = 0F; //左倾斜文字
            float shearY = -0.3F;
            transform.Shear(shearX, shearY);
            g.Transform = transform;
            g.DrawString(addText, f, b, 0, map.Height / 2);

            g.Dispose();

            //保存加水印过后的图片
            string newPath = string.Format(@"{0}\_{1}_{2}_{3}_{4}_{5}_{6}_\",
                    Environment.GetEnvironmentVariable("Temp"),
                    DateTime.Now.Year,
                    DateTime.Now.Month,
                    DateTime.Now.Day,
                    DateTime.Now.Hour,
                    DateTime.Now.Minute,
                    DateTime.Now.Second);
            if (!System.IO.Directory.Exists(newPath))
                System.IO.Directory.CreateDirectory(newPath);
            newPath += "temp.jpg";
            map.Save(newPath);
            map.Dispose();

            Image img = Image.FromFile(newPath);
            PictureBox pb = new PictureBox();
            pb.BackColor = Color.Transparent;
            pb.Size = img.Size;
            pb.Image = img;
            pb.Parent = windown;
            pb.Location = new Point(windown.Width - pb.Width * 2, 5);
            pb.BringToFront();
            windown.Disposed += (sender, e) =>
            {
                pb.Dispose();
                img.Dispose();
            };
        }

        #endregion

        #region [身份证验证]

        /// <summary>
        /// 验证身份证是否有效
        /// </summary>
        /// <param name="Id">身份证号码</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool CheckCardID(string Id, ref string msg)
        {
            if (Id.Length == 18)//|| Id.Length == 15
            {
                return CheckingCardID(Id, ref msg);
            }
            msg = "非法证件格式！";
            return false;
        }

        /// <summary>
        /// 验证身份证号码
        /// </summary>
        /// <param name="Id">身份证号码</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private static bool CheckingCardID(string Id, ref string msg)
        {
            long n = 0;
            if (!long.TryParse(Id.Remove(17), out n)
                || (n < Math.Pow(10, 16))
                || !long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n)
                || (!long.TryParse(Id, out n)
                || (n < Math.Pow(10, 14))))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            string city = "北京;吉林;福建;广东;云南;天津;黑龙江;江西;广西; 西藏;河北;上海;山东;海南;陕西;山西;江苏;河南;重庆;甘肃;内蒙古;浙江;湖北;四川;青海;辽宁;安徽;湖南;贵州;宁夏;新疆;台湾;香港;澳门;国外";
            Dictionary<int, string> cityDirectory = new Dictionary<int, string>();
            string[] addressNums = address.Split('x');
            string[] citys = city.Split(';');
            for (int i = 0; i < addressNums.Length; i++)
            {
                cityDirectory.Add(int.Parse(addressNums[i]), citys[i]);
            }
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                msg = "非法证件格式，无效的地区！";
                return false;//省份验证
            }
            msg += cityDirectory[Convert.ToInt32(Id.Substring(0, 2))] + ";";
            if (Id.Length == 18)
            {
                string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birth, out time) == false)
                {
                    msg = "非法证件格式，无效的出生日期！";
                    return false;//生日验证
                }
                string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
                string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
                char[] Ai = Id.Remove(17).ToCharArray();
                int sum = 0;
                for (int i = 0; i < 17; i++)
                {
                    sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
                }
                int y = -1;
                Math.DivRem(sum, 11, out y);
                if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
                {
                    msg = "非法的证件格式!";
                    return false;//校验码验证
                }
                msg += birth + ";";
                int a17 = int.Parse(Id.Substring(16, 1));
                if ((a17 % 2) == 1)
                    msg += "男";
                else
                    msg += "女";
            }
            else if (Id.Length == 15)
            {
                string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birth, out time) == false)
                {
                    msg = "非法证件格式，无效的出生日期！";
                    return false;//生日验证
                }
                int a15 = int.Parse(Id.Substring(14, 1));
                if ((a15 % 2) == 1)
                    msg += "男";
                else
                    msg += "女";
            }
            return true;//符合GB11643-1999标准
        }

        #endregion

    }
}
